package com.example.transaction.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.transaction.common.vo.Result;
import com.example.transaction.sys.entity.*;
import com.example.transaction.sys.service.IAddressService;
import com.example.transaction.sys.service.IItemImageService;
import com.example.transaction.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/sys/itemImage")
public class itemImageController {


    @Autowired
    private IItemImageService itemImageService;


    /**
     * 增加商品图片
     * @param itemImage
     * @return
     */
    @CacheEvict(value = "itemImage", key = "#itemImage.itemID",allEntries = true)
    @PostMapping
    public Result<String> addItemImage(@RequestBody ItemImage itemImage){
        try {
            itemImageService.save(itemImage);
        }catch (Exception e){
            return Result.fail("增加图片失败");
        }
        return Result.success("增加图片成功");
    }

    /**
     * 根据itemID获取所有图片
     * @param itemID
     * @return
     */
    @Cacheable(value = "itemImage", key = "#itemID")
    @GetMapping("/{itemID}")
    public Result<List<ItemImage>> getItemImagesByItemID(@PathVariable("itemID")String itemID){
        LambdaQueryWrapper<ItemImage> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(itemID),ItemImage::getItemID,itemID);
        List<ItemImage> itemImages=itemImageService.list(wrapper);
        return Result.success(itemImages);
    }

    /**
     * 根据itemImageURL删除对应图片
     * @param itemImageURL
     * @return
     */
    @CacheEvict(value = "itemImage",allEntries = true)
    @DeleteMapping("/itemImageURL")
    public Result<ItemImage>deleteCommentById(@RequestParam("itemImageURL")String itemImageURL){
        LambdaQueryWrapper<ItemImage> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(itemImageURL),ItemImage::getItemImageURL,itemImageURL);
        List<ItemImage> itemImageID = itemImageService.list(wrapper);
        itemImageService.removeById(itemImageID.get(0));
        return Result.success("删除图片成功");
    }


}
